package root.electronclass.electronclass.personal.activity.model

import androidx.lifecycle.*
import root.electronclass.electronclass.mvp.entity.ExamSummary
import root.electronclass.electronclass.ext.CoroutineExceptionHandler
import root.electronclass.electronclass.personal.PersonRepository
import kotlinx.coroutines.launch

/**
 *@ClassName TODO
 *@Description TODO
 *@Author caofc
 *@Date 2023/3/24 20:59
 */
class PersonModel : ViewModel() {

    private val _data = MediatorLiveData<Pair<Int, List<ExamSummary>>>()
    val data: LiveData<Pair<Int, List<ExamSummary>>> = _data

    private val pageIndex = MutableLiveData(1)

    private var type: Int = 1// 1-近7天 2-近30天 3-一学期

    init {
        load(page = 1)
    }


    fun load(type: Int = this.type,  page: Int = (pageIndex.value ?: 1) + 1) {
        this.type = type
        pageIndex.value = page
        loadData(type)
    }

    private fun loadData(type: Int) {
        viewModelScope.launch(CoroutineExceptionHandler() { pageIndex.value = ((pageIndex.value ?: 1) - 1).coerceAtLeast(1) }) {
            _data.value = pageIndex.value!! to PersonRepository.examPage(pageIndex.value!!, type)
            pageIndex.value = (pageIndex.value ?: 1) + 1
        }
    }
}